package com.kunlun.basedata.organize.service.impl;

import com.kunlun.basedata.limit.model.CorrelateModel;
import com.kunlun.basedata.limit.service.ICorrelateService;
import com.kunlun.basedata.organize.dao.ICompanyDao;
import com.kunlun.basedata.organize.model.CompanyModel;
import com.kunlun.basedata.organize.service.ICompanyService;
import com.kunlun.basedata.utils.CommonUtil;
import com.kunlun.common.model.Page;
import com.kunlun.common.utils.TreeUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 部门业务Service类
 */
@Service
@Transactional
public class CompanyService implements ICompanyService {

    private final Logger logger = LogManager.getLogger();

    @Autowired
    private ICompanyDao companyDao;
    @Lazy
    @Autowired
    private ICorrelateService correlateService;

    @Override
    public Page<CompanyModel> getCompanyPage(CompanyModel companyModel, int currentPage, int pageSize) throws Exception {
        int startIndex = (currentPage - 1) * pageSize;
        Map<String, Object> queryMap = CommonUtil.packageQueryMap(companyModel, startIndex, pageSize);
        List<CompanyModel> allCompany = companyDao.getCompanyList(queryMap);
        List<CompanyModel> companyModels = TreeUtil.buildTree(allCompany);
        int size = companyModels.size();

        int maxIndex = startIndex + pageSize;
        Page<CompanyModel> page = new Page<>();
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        page.setTotal(size);
        page.setRecords(companyModels.subList(startIndex, maxIndex > size ? size : maxIndex));
        return page;
    }

    @Override
    public void addCompany(CompanyModel companyModel) throws Exception {
        companyModel.setId(CommonUtil.generateUUID());
        String longCode = StringUtils.isEmpty(companyModel.getParentId()) ? companyModel.getId() : (companyModel.getLongCode() + "_" + companyModel.getId());
        companyModel.setLongCode(longCode);
        companyDao.addCompany(companyModel);

        CorrelateModel correlateModel = new CorrelateModel(companyModel);
        correlateService.addCorrelate(correlateModel);
    }

    @Override
    public void updateCompany(CompanyModel companyModel) throws Exception {
        companyDao.updateCompany(companyModel);
    }

    @Override
    public void deleteCompany(List<String> list) throws Exception {
        companyDao.deleteCompany(list);
    }

    @Override
    public List<CompanyModel> getCompanyList(Map<String, Object> queryMap) throws Exception {
        return companyDao.getCompanyList(queryMap);
    }
}
